package com.zhongxi.guoyuan.view.personalCenter;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class PersonAboutUsActivity extends BaseActivity {

    private RelativeLayout rlGo;
    private String type;
    private UpdateResult result;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_person_about_us);
        initTitle();
        tvTitle.setText(getString(R.string.person_text_aboutUs));
        rlGo= (RelativeLayout) findViewById(R.id.rl_go);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        rlGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = "update";
                getServer(Url.CHECK_UPD, null, "", false, null, "get");
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson=new Gson();
        if ("update".equals(type)) {
            result = gson.fromJson(response, UpdateResult.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (null != result.getUpdClient() && !"".equals(result.getUpdClient())) {
                if (null != result.getUpdClient().getDownUrl() && !"".equals(result.getUpdClient().getDownUrl())) {
                    downFile();
                }
            } else {
                isExists();
            }
        }
    }

    private void downFile2() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        tv_dsc.setText("发现新版本，请尽快更新");
        final AlertDialog dialog = adb.create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk2();
            }
        });
        dialog.show();
    }

    /**
     * 是否需要更新
     */
    int version = 0;
    HttpURLConnection conn = null;

    private void isExists() {
        version = Integer.parseInt(MyApplication.getInstance().getMinVersion()) + 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(Url.APK_URL + version + Url.APK_URL_NAME);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                downFile2();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("已是最新版本");
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                finish();
                return true;
            } else {
                return false;
            }
        }
    };

    private void downLoadApk2() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(Url.APK_URL + version + Url.APK_URL_NAME, pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void downFile() {
        AlertDialog.Builder adb = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        if (null != result.getUpdClient().getDesc() && !"".equals(result.getUpdClient().getDesc())) {
            tv_dsc.setText(result.getUpdClient().getDesc());
        } else {
            tv_dsc.setText("发现新版本,请尽快更新");
        }
        final AlertDialog dialog = adb.create();
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk();
            }
        });
        dialog.show();
    }

    /**
     * 下载APK
     */
    private void downLoadApk() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(result.getUpdClient().getDownUrl(), pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //安装apk
    protected void installApk(File file) {
        if (file != null) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, "com.zhongxi.guoyuan.fileprovider", file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent intent = new Intent();
                //执行动作
                intent.setAction(Intent.ACTION_VIEW);
                //执行的数据类型
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }
}
